package com.hu.ta.assignment5.beans;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class PosProbabilities implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4774996918037196667L;

	private Tuple<String, Double>[] list;

	private Map<String, Integer> frequencies;

	public PosProbabilities() {
		list = new Tuple[0];
	}

	public void add(String str) {
		if (frequencies == null) {
			frequencies = new HashMap<String, Integer>();
		}
		Integer n;
		if (frequencies.containsKey(str)) {
			n = frequencies.get(str) + 1;
		} else {
			n = 1;
		}
		frequencies.put(str, n);
	}

	@SuppressWarnings("unchecked")
	public void frequencies2Probabilities() {
		int all = 0;
		for (int f : frequencies.values()) {
			all += f;
		}

		list = new Tuple[frequencies.size()];

		int i = 0;
		for (Map.Entry<String, Integer> f : frequencies.entrySet()) {
			list[i++] = new Tuple<String, Double>(f.getKey(),
					(double) f.getValue() / all);
		}
	}

	public double getProbability(String tag) {
		for (Tuple<String, Double> entry : list) {
			if (entry.getX().equals(tag)) {
				return entry.getY();
			}
		}
		// TODO: Smoothing
		return 0.01E-10;
	}

	public Tuple<String, Double>[] getList() {
		return list;
	}

	@Override
	public String toString() {
		String ret = "Tag\tProbability\n";
		for (Tuple<String, Double> t : list) {
			ret += t.getX() + "\t|\t" + t.getY() + "\t|\n";
		}
		return ret;
	}

	public String[] toStrings() {
		String ret[] = new String[list.length];
		int i = 0;
		for (Tuple<String, Double> t : list) {
			ret[i++] = t.getX() + "\t" + String.format("%1$,.2f", t.getY())
					+ "\n";
		}
		return ret;
	}
}
